import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { shortToken } from './api'
// import { BASE_URL, TIMEOUT } from "./request";
const get_access_token = async () => {
  let res = await shortToken({})
  localStorage.setItem('access_token', res.data.access_token)
  return res
}

const service = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 10000
});


// http request 拦截器
service.interceptors.request.use(config => {
  // 发送网络请求时, 在界面的中间位置显示Loading的组件,使用ant-design插件，这里不再赘述
  //请求携带的信息
  let access_token = localStorage.getItem('access_token');
  let REFRESH_token = localStorage.getItem('refresh_token');
  config.headers['Authorization'] = `short+${access_token} length+${REFRESH_token}`;
  return config
}, err => {
  //...关闭加载loading的组件，显示消息提示弹窗
  return err;
});


// http response 拦截器
service.interceptors.response.use(res => {
  if (res.data.code === 1001) {
    console.log("未授权访问");
  } else if (res.data.code === 1002) {
    get_access_token()
  } else if (res.data.code === 1003) {
    console.log("短token过期,且没有长token");
  } else if (res.data.code === 1004) {
    console.log("长token过期");
  }else if(res.data.code==2000){
    localStorage.setItem('access_token', res.data.access_token)
  }
  return res.data;
}, err => {
  if (err && err.response) {
    console.log(err.response.status);
  }
  return err;
});


export default service;
